<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<!-- <cl-add-btn /> -->
			<el-button type="primary" @click="showAppointDialog">新增</el-button>
			<!-- 删除按钮 -->
			<!-- <cl-multi-delete-btn /> -->
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
		<week-appoint-dialog
			v-model="weekAppointVisible"
			:doctor-id="currentDoctorId"
			:shop-id="currentShopId"
			@select="handleTimeSelect"
		/>
		<el-dialog v-model="visible" :title="t('班级学员')" width="80%">
			<el-table :data="students" :border="true" style="width: 100%">
				<el-table-column prop="name" :label="t('学员姓名')" />
				<el-table-column prop="phone" :label="t('手机号')" />
				<el-table-column prop="trainCount" :label="t('训练次数')" />
				<el-table-column prop="giftCount" :label="t('赠送次数')" />
				<el-table-column prop="appointTime" :label="t('报名时间')" />
				<el-table-column prop="signStatusText" :label="t('签到状态')" />
				<el-table-column :label="t('操作')" width="200">
					<template #default="scope">
						<template v-if="scope.row.signStatus !== 1">
							<el-button type="primary" size="small" @click="handleSignIn(scope.row)">
								{{ t('签到') }}
							</el-button>
							<el-button type="danger" size="small" @click="handleQuit(scope.row)">
								{{ t('退班') }}
							</el-button>
						</template>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
		<!--预约弹窗-->
		<class-time-dialog
			v-model="appointDialogVisible"
			:student-id="currentStudentId"
			@success="refresh"
		/>
	</cl-crud>
</template>

<script lang="tsx" setup>
defineOptions({
	name: 'class-class'
});

import { useDict } from '/$/dict';
import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import WeekAppointDialog from '../../student/components/WeekAppointDialog.vue';
import ClassTimeDialog from '../components/ClassTimeDialog.vue';

const { service } = useCool();
const { t } = useI18n();
// 学员列表弹窗控制
const visible = ref(false);
const loading = ref(false);
const students = ref([]);
const currentClassId = ref('');

// 添加新的响应式变量和方法
const weekAppointVisible = ref(false);
const currentDoctorId = ref('');
const currentShopId = ref('');
const appointDialogVisible = ref(false);
const currentStudentId = ref(0);

// 学员表格列配置
const studentColumns = [
	{ label: t('学员姓名'), prop: 'name' },
	{ label: t('手机号'), prop: 'phone' },
	{ label: t('训练次数'), prop: 'trainCount' },
	{ label: t('赠送次数'), prop: 'giftCount' },
	{
		label: t('报名时间'),
		prop: 'appointTime',
		component: { name: 'cl-date-text' }
	},
	{
		label: t('操作'),
		type: 'op',
		buttons: [
			{
				label: t('签到'),
				type: 'primary',
				onClick: ({ scope }) => {
					handleSignIn(scope.row);
				}
			},
			{
				label: t('退班'),
				type: 'danger',
				onClick: ({ scope }) => {
					handleQuit(scope.row);
				}
			}
		]
	}
];

// 选项
const options = reactive({
	status: [
		{ label: t('开启'), value: 1 },
		{ label: t('关闭'), value: 0 }
	],
	doctorList: []
});
const { dict } = useDict();
const disabled = ref(true);

function showAppointDialog(studentId) {
	currentStudentId.value = studentId;
	appointDialogVisible.value = true;
}
// cl-upsert
const Upsert = useUpsert({
	items: [
		// {
		// 	label: '选择日期', // 不显示标签
		// 	prop: 'timeSelect',
		// 	component: (
		// 		<el-button class="el-button--primary" onClick={() => showAppointDialog()}>
		// 			选择时间
		// 		</el-button>
		// 	),
		// 	span: 8,
		// 	value: t('选择时间')
		// },
		{
			label: t('门店'),
			prop: 'shopId',
			component: {
				name: 'el-select',
				options: dict.get('Shop')
			},
			span: 8
		},
		{
			label: t('医生'),
			prop: 'doctorId',
			component: {
				name: 'el-select',
				options: options.doctorList
			},
			span: 8
		},
		{
			label: t('班级名称'),
			prop: 'className',
			component: { name: 'el-input', props: { clearable: true } },
			span: 8,
			required: true,
			value: '视力训练课'
		},
		{
			label: t('上课日期'),
			prop: 'classDate',
			component: {
				name: 'el-date-picker',
				props: {
					type: 'date',
					valueFormat: 'YYYY-MM-DD',
					defaultValue: new Date()
				}
			},
			span: 8,
			value: new Date().toISOString().split('T')[0]
		},
		{
			label: t('上课时间'),
			prop: 'beginTime',
			component: {
				name: 'el-time-picker',
				props: {
					format: 'HH:mm',
					valueFormat: 'HH:mm',
					defaultValue: new Date(new Date().setMinutes(0, 0, 0)), // 设置为当前小时的整点
					placeholder: '选择时间'
				}
			},
			span: 8
		},
		// {
		// 	label: t('下课时间'),
		// 	prop: 'endTime',
		// 	component: {
		// 		name: 'el-time-picker',
		// 		props: {
		// 			format: 'HH:mm',
		// 			valueFormat: 'HH:mm',
		// 			defaultValue: new Date(new Date().setMinutes(0, 0, 0)), // 设置为当前小时的整点
		// 			placeholder: '选择时间'
		// 		}
		// 	},
		// 	span: 8
		// },
		// {
		// 	label: '上课时长',
		// 	prop: 'classTime',
		// 	component: {
		// 		name: 'el-input',
		// 		props: { disabled }
		// 	},
		// 	value: '60分钟',
		// 	span: 8
		// },
		// {
		// 	label: t('下课时间'),
		// 	prop: 'endTime',
		// 	component: {
		// 		name: 'el-time-picker',
		// 		props: {
		// 			format: 'HH:mm',
		// 			valueFormat: 'HH:mm',
		// 			defaultValue: new Date(new Date().setHours(new Date().getHours() + 1, 0, 0, 0)), // 设置为下一个小时的整点
		// 			placeholder: '选择时间'
		// 		}
		// 	},
		// 	span: 8
		// },
		{
			label: t('人员限额'),
			prop: 'limitCount',
			hook: 'number',
			component: { name: 'el-input-number', props: { min: 0 } },
			span: 8,
			required: true,
			value: 5
		},
		{
			label: t('状态'),
			prop: 'status',
			component: { name: 'el-radio-group', options: options.status },
			value: 1,
			required: true
		}
	],
	onOpen() {
		service.doctor.info.getSelectlist({ shopId: 0 }).then((res: any) => {
			if (res) {
				const doctorItem = Upsert.value.items.find(item => item.prop === 'doctorId');
				doctorItem.component.options = res;
			}
			// 如果是编辑模式，需要处理时间拆分
			if (Upsert.value.form.startTime) {
				// 拆分开始时间为日期和时间
				const startDateTime = new Date(Upsert.value.form.startTime);

				// 设置日期
				Upsert.value.form.classDate = startDateTime.toISOString().split('T')[0];

				// 设置开始和结束时间
				Upsert.value.form.beginTime =
					startDateTime.getHours().toString().padStart(2, '0') +
					':' +
					startDateTime.getMinutes().toString().padStart(2, '0');
			}
		});
	},
	onSubmit(data, { done, close, next }) {
		// 计算结束时间（开始时间后1小时）
		const [hours, minutes] = data.beginTime.split(':').map(Number);
		const endHours = hours + 1;
		const endTime = `${endHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;

		next({
			...data,
			startTime: `${data.classDate} ${data.beginTime}:00`,
			endTime: `${data.classDate} ${endTime}:00`
		});
	}
});

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection' },
		{ label: t('门店'), prop: 'shopId', dict: dict.get('Shop'), minWidth: 140 },
		{ label: t('医生'), prop: 'doctorName', minWidth: 140 },
		{ label: t('班级名称'), prop: 'className', minWidth: 140 },
		{
			label: t('上课时间'),
			prop: 'startTime',
			minWidth: 170,
			sortable: 'custom',
			component: { name: 'cl-date-text' }
		},
		{
			label: t('下课时间'),
			prop: 'endTime',
			minWidth: 170,
			sortable: 'custom',
			component: { name: 'cl-date-text' }
		},
		{
			label: t('人员限额'),
			prop: 'limitCount',
			minWidth: 140,
			sortable: 'custom'
		},
		{
			label: t('当前人数'),
			prop: 'currentCount',
			minWidth: 140,
			sortable: 'custom'
		},
		{
			label: t('状态'),
			prop: 'status',
			minWidth: 120,
			dict: options.status
		},
		// {
		// 	label: t('创建时间'),
		// 	prop: 'createTime',
		// 	minWidth: 170,
		// 	sortable: 'desc',
		// 	component: { name: 'cl-date-text' }
		// },
		// {
		// 	label: t('更新时间'),
		// 	prop: 'updateTime',
		// 	minWidth: 170,
		// 	sortable: 'custom',
		// 	component: { name: 'cl-date-text' }
		// },
		{
			type: 'op',
			buttons: [
				{
					label: t('查看学员'),
					type: 'success',
					onClick: ({ scope }) => {
						viewStudents(scope.row);
					}
				},
				'edit'
			],
			width: 200
		}
	]
});

// cl-search
const Search = useSearch({
	items: [
		{
			prop: 'shopId',
			component: {
				name: 'cl-select',
				props: { options: dict.get('Shop'), placeholder: '门店' }
			}
		},
	]
});

// cl-crud
const Crud = useCrud(
	{
		service: service.class.class
	},
	app => {
		app.refresh();
	}
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
// 查看学员方法
async function viewStudents(row: any) {
	currentClassId.value = row.id;
	visible.value = true;
	loading.value = true;

	try {
		const res = await service.class.classAppoint.getClassStudents({
			classId: row.id
		});
		students.value = res;
		console.log('viewStudents', res, students);
	} catch (err) {
		ElMessage.error(t('获取学员列表失败'));
	} finally {
		loading.value = false;
	}
}
// 签到方法
async function handleSignIn(row: any) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要为该学员签到吗？'), t('签到确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});

		// 用户确认后继续签到流程
		await service.class.classAppoint.signIn({
			appointId: row.appointId
		});
		ElMessage.success(t('签到成功'));
		viewStudents({ id: currentClassId.value });
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err !== 'cancel') {
			ElMessage.error(err.message || t('签到失败'));
		}
	}
}

// 退班方法
async function handleQuit(row: any) {
	ElMessageBox.confirm(t('确认要将该学员退班吗？'), t('提示'), {
		type: 'warning'
	})
		.then(async () => {
			try {
				await service.class.classAppoint.cancelAppoint({
					id: row.appointId
				});
				ElMessage.success(t('退班成功'));
				viewStudents({ id: currentClassId.value });
			} catch (err: any) {
				ElMessage.error(err.message || t('退班失败'));
			}
		})
		.catch(() => {});
}

// 处理时间选择
function handleTimeSelect(time: string) {
	if (time) {
		Upsert.value.form.beginTime = time;
	}
	weekAppointVisible.value = false;
}
</script>
